import pandas as pd
from docx import Document
from docx.shared import Pt, RGBColor, Cm, Inches

from utils.analysis.describe_analysis import describe
from utils.report.base import convert_str_to_float_3, delete_table_first_last_row, set_cell_border, create_table, \
    format_table


def _generate_report(data, document, table_count):
    p1 = (
        f"多重响应用于多选题分析,分析多选题各项的选择比例情况等;共涉及到两个名词，分别是响应率和普及率，响应率用于对比各个选项的相对选择比例"
        f"情况，普及率用于某项的选择普及情况，二者的区别在于被除数不一样。（比如有100个样本，平均每个样本选择3项，则总共100个样本共选择了"
        f"300个选项。以及对于某个选项共有60个样本选择，则响应率=60/300=20%； 普及率=60/100=60%）。"
    )
    document.add_paragraph(p1)  # 插入段落
    document.add_paragraph(
        "第一：分析响应率情况，即多选题各选项的选择比例，重点描述比例较高项；（响应率加和一定为100%）")  # 插入段落
    document.add_paragraph(
        "第二：分析普及率，即整体上看，多选题各选项占所有选择的比例情况，重点分析选择比例较高项；（普及率加和通常会高于100%）")  # 插入段落
    _generate_table1(data, document, table_count)  # 表1
    return


def _generate_table1(data, document, table_count):
    # 新建表格
    init_rows = 3
    init_cols = 5
    # table = document.add_table(rows=init_rows, cols=init_cols)
    table = create_table(doc=document, row=init_rows, col=init_cols)
    # 1. 填充1-3行
    # 填充第一行表头
    row = table.rows[0]  # 表格
    f_cell = None
    for i in range(init_cols):  # 合并单元格
        if i == 0:
            f_cell = table.cell(0, 0)
        else:
            f_cell.merge(table.cell(0, i))
    frequency_table_name = ""
    row.cells[0].text = frequency_table_name + '响应率和普及率汇总表格'
    # 填充第二行
    table.cell(1, 0).merge(table.cell(2, 0)).text = "名称"
    table.cell(1, 1).merge(table.cell(2, 1)).text = "选项"
    table.cell(1, 2).merge(table.cell(1, 3)).text = "响应"
    # table.cell(1, 3).text = "均值"
    table.cell(1, 4).merge(table.cell(2, 4)).text = "普及率%"
    table.cell(2, 2).text = "n"
    table.cell(2, 3).text = "响应率%"
    start_index = 3
    for k, values in data.items():
        for ci in values:
            table.add_row()  # 表格动态增加一行
            cur_row = table.rows[-1]
            cur_row.cells[1].text = ci.get('选项')
            cur_row.cells[2].text = convert_str_to_float_3(ci.get('n'))
            cur_row.cells[3].text = convert_str_to_float_3(ci.get('响应率'))
            cur_row.cells[4].text = convert_str_to_float_3(ci.get('普及率'))
        table.cell(start_index, 0).text = k
        if len(values) > 1:
            for i in range(len(values) - 1):
                table.cell(start_index + i, 0).merge(table.cell(start_index + i + 1, 0))
        start_index += len(values)
    format_table(table)
    add_three_lines_table(table)
    return table


def add_three_lines_table(table):
    delete_table_first_last_row(table)
    first_row = table.rows[1]
    second_row = table.rows[3]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    for cell in second_row.cells:
        set_cell_border(cell, top={"sz": 4, "color": "#000000", "val": "single", "space": "0"})
    last_row = table.rows[-1]
    for cell in last_row.cells:
        set_cell_border(cell, bottom={"sz": 12, "val": "single", "color": "#000000", "space": "0"})
    return


def generate(src_data, doc, table_count):
    title1 = doc.add_heading(level=1)  # 增加标题
    t1_run = title1.add_run('多重响应')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)
    _generate_report(src_data, doc, table_count)  # 生成表格
    return


if __name__ == '__main__':
    # 创建 Document 对象，等价于在电脑上打开一个 Word 文档
    doc = Document()
    pd.set_option('expand_frame_repr', False)

    pd.set_option('expand_frame_repr', False)
    df = pd.read_excel('./test_datas.xlsx')
    src_data = describe(df)
    title1 = doc.add_heading(level=1)  # 增加标题
    t1_run = title1.add_run('多重响应')
    t1_run.font.color.rgb = RGBColor(10, 10, 10)

    # 保存文档
    doc.save('demo.docx')
